import { asyncRoutes, constantRoutes } from '@/router'
import {inArray,isType } from '@/utils/util'
import {getAllByRole} from '@/api/permission'
import store from '@/store'
/**
 * Use meta.role to determine if the current user has permission
 * @param roles
 * @param route
 */
function hasPermission(route) {
  for(let p of state.permissions){
    console.log(p, route)
    var o1 = p.Policy.Path.split('/').filter(item => item != ''&&item !='api').join('/')
    var o2 = route.path.split('/').filter(item => item != '').join('/')
    
    // console.log(o1, o2)
    return o1==o2
  }
}
import { Form } from 'element-ui'




/**
 * Filter asynchronous routing tables by recursion
 * @param routes asyncRoutes
 * @param roles
 */
export function filterAsyncRoutes(routes, roles) {
  const res = []

  routes.forEach(route => {
    const tmp = { ...route }
    if (hasPermission(roles, tmp)) {
      if (tmp.children) {
        tmp.children = filterAsyncRoutes(tmp.children, roles)
      }
      res.push(tmp)
    }
  })

  return res
}

const state = {
  routes: [],
  addRoutes: [],
  permissions: []
}

const mutations = {
  SET_ROUTES: (state, routes) => {
    state.addRoutes = routes
    state.routes = constantRoutes.concat(routes)
  },
  SET_PERMISSIONS: (state, permissions) => {
    state.permissions = permissions
  }
}

const actions = {
  generateRoutes({ commit }) {
    return new Promise((resolve, reject) => {
      getAllByRole({roles: store.getters.roles.join(',')}).then(res=>{
        if(res.code==0){
          let accessedRoutes = new Array()
          let permissions = res.data
          if (isType(permissions, Array)) {
            commit('SET_PERMISSIONS', permissions)
            if (isType(asyncRoutes, Array)) {
              for(let r of asyncRoutes){
                if(hasPermission(r)){

                  accessedRoutes.push(r)
                }
              }
            }
            commit('SET_ROUTES', accessedRoutes) 
          
            resolve(accessedRoutes)
          } else{
            reject("获取权限失败")
          }
        }else{
          reject(res.msg)  
        }
      }).catch(err=>{
        reject(err)
      })
    })
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}
